package com.ktvme.processInstance;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.ktvme.core.AbstractOperator;
import com.ktvme.core.DolphinException;
import com.ktvme.result.PageResult;
import com.ktvme.core.DolphinClientConstant;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
public class ProcessInstanceOperator extends AbstractOperator {

    public ProcessInstanceOperator(String url, String token) {
        super(url, token);
    }

    /**
     * 启动流程实例
     *
     * @param projectCode 项目 Code
     * @param processInstanceCreateParam 流程实例创建参数（作为查询参数）
     * @return 是否启动成功
     */
    public Boolean startProcessInstance(Long projectCode, ProcessInstanceCreateParam processInstanceCreateParam) {
        String url = baseUrl + "/projects/" + projectCode + "/executors/start-process-instance";
        log.info("启动流程实例, URL: {}", url);

        try {
            // 将 ProcessInstanceCreateParam 对象转换为 Map
            Map<String, Object> queryParams = BeanUtil.beanToMap(processInstanceCreateParam, false, true);

            // 发送 POST 请求并带上查询参数
            HttpResponse response = HttpRequest.post(url)
                    .header("token", token)
                    .form(queryParams) // 使用 form 方法传递查询参数
                    .execute();

            if (response.isOk()) {
                JSONObject jsonResponse = JSONUtil.parseObj(response.body());
                return jsonResponse.getBool("success");
            } else {
                throw new IOException("HTTP request failed with status code: " + response.getStatus());
            }
        } catch (IOException e) {
            throw new DolphinException("启动流程实例失败", e);
        }
    }

    /**
     * 分页查询流程实例列表
     */
    public PageResult<ProcessInstanceQueryResp> page(
            Long projectCode, Long workflowCode, Integer pageNo, Integer pageSize, 
            String searchVal, String stateType, String startDate, String endDate) {

        String url = baseUrl + "/projects/" + projectCode + "/process-instances";
        log.info("构建的请求URL: {}", url);

        // 构建请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("pageNo", pageNo);
        params.put("pageSize", pageSize);
        
        // 添加可选参数
        if (workflowCode != null) {
            params.put("processDefineCode", workflowCode);
        }
        if (searchVal != null && !searchVal.trim().isEmpty()) {
            params.put("searchVal", searchVal.trim());
        }
        if (stateType != null && !stateType.trim().isEmpty()) {
            params.put("stateType", stateType.trim());
        }
        if (startDate != null && !startDate.trim().isEmpty()) {
            params.put("startDate", startDate.trim());
        }
        if (endDate != null && !endDate.trim().isEmpty()) {
            params.put("endDate", endDate.trim());
        }
        
        log.info("请求参数: {}", params);

        try {
            // 发送 GET 请求
            HttpResponse response = HttpRequest.get(url)
                    .header("token", token)
                    .form(params) // 使用 form 方法传递参数
                    .execute();
            log.info("发送GET请求，响应状态码: {}", response.getStatus());

            if (response.isOk()) {
                JSONObject jsonObject = JSONUtil.parseObj(response.body());
                log.info("响应体: {}", response.body());

                if (jsonObject == null || !jsonObject.containsKey("data")) {
                    log.error("响应数据为空或格式不正确");
                    throw new DolphinException("响应数据为空或格式不正确");
                }

                JSONObject data = jsonObject.getJSONObject("data");
                log.info("解析后的数据: {}", data);

                List<ProcessInstanceQueryResp> javaList = data.getJSONArray("totalList")
                        .toList(ProcessInstanceQueryResp.class);
                log.info("转换后的流程实例列表: {}", javaList);

                PageResult<ProcessInstanceQueryResp> pageResult = new PageResult<>();
                pageResult.setRecords(javaList);
                pageResult.setCurrentPage(pageNo);
                pageResult.setPageSize(pageSize);
                pageResult.setTotalPages(data.getInt("totalPage"));
                pageResult.setTotalRecord(data.getInt("total"));
                log.info("构建的PageResult对象: {}", pageResult);

                return pageResult;
            } else {
                log.error("HTTP request failed with status code: {}", response.getStatus());
                throw new IOException("HTTP request failed with status code: " + response.getStatus());
            }
        } catch (IOException e) {
            log.error("获取流程实例列表失败", e);
            throw new DolphinException("获取流程实例列表失败", e);
        }
    }

    /**
     * 重新运行流程实例
     */
    public Boolean reRunProcessInstance(long projectCode, long processInstanceId) {
        return executeProcessInstance(projectCode, processInstanceId, DolphinClientConstant.ExecuteType.RE_RUN);
    }

    /**
     * 停止流程实例
     */
    public Boolean stopProcessInstance(long projectCode, long processInstanceId) {
        log.info("停止流程实例, ID: {}", processInstanceId);
        return executeProcessInstance(projectCode, processInstanceId, DolphinClientConstant.ExecuteType.STOP);
    }

    /**
     * 暂停流程实例
     */
    public Boolean pauseProcessInstance(long projectCode, long processInstanceId) {
        log.info("暂停流程实例, ID: {}", processInstanceId);
        return executeProcessInstance(projectCode, processInstanceId, DolphinClientConstant.ExecuteType.PAUSE);
    }

    /**
     * 执行流程实例操作（如：重启、停止、暂停）
     */
    private Boolean executeProcessInstance(long projectCode, long processInstanceId, String executeType) {
        String url = baseUrl + "/projects/" + projectCode + "/executors/execute";
        log.debug("构建请求URL: {}", url);

        // 构建请求参数
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("processInstanceId", processInstanceId);
        queryParams.put("executeType", executeType);
        log.debug("创建请求参数对象: processInstanceId={}, executeType={}", processInstanceId, executeType);

        try {
            // 发送 POST 请求并带上查询参数
            HttpResponse response = HttpRequest.post(url)
                    .header("token", token)
                    .form(queryParams) // 使用 form 方法传递查询参数
                    .execute();
            log.debug("发送POST请求到URL: {}", url);

            if (response.isOk()) {
                JSONObject jsonResponse = JSONUtil.parseObj(response.body());
                log.debug("响应体: {}", jsonResponse.toString());
                return jsonResponse.getBool("success");
            } else {
                log.error("HTTP request failed with status code: {}", response.getStatus());
                throw new IOException("HTTP request failed with status code: " + response.getStatus());
            }
        } catch (IOException e) {
            log.error("{} 流程实例失败", executeType, e);
            throw new DolphinException(executeType + " 流程实例失败", e);
        }
    }

    /**
     * 删除流程实例
     */
    public Boolean deleteProcessInstance(long projectCode, long processInstanceId) {
        String url = baseUrl + "/projects/" + projectCode + "/process-instances/" + processInstanceId;
        log.info("删除流程实例, ID: {}, URL: {}", processInstanceId, url);

        try {
            // 发送 DELETE 请求
            HttpResponse response = HttpRequest.delete(url)
                    .header("token", token)
                    .execute();

            if (response.isOk()) {
                JSONObject jsonResponse = JSONUtil.parseObj(response.body());
                return jsonResponse.getBool("success");
            } else {
                throw new IOException("HTTP request failed with status code: " + response.getStatus());
            }
        } catch (IOException e) {
            throw new DolphinException("删除流程实例失败", e);
        }
    }
}